
public class SyncMethodThreadCommunication {
	static class DataWrap{
		int data = 0;
		boolean flag = false;
		
		public synchronized void addThreadA(){
			if (flag) {
				try {
					wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} 
			
			data++;
			System.out.println(Thread.currentThread().getName() + " " + data);
			flag = true;
			notify();
		}
		
		public synchronized void addThreadB() {
			if (!flag) {
				try {
					wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} 
			
			data++;
			System.out.println(Thread.currentThread().getName() + " " + data);
			flag = false;
			notify();
		}
	}
	
	static class ThreadA extends Thread {
		private DataWrap data;
		
		public ThreadA(DataWrap dataWrap) {
			this.data = dataWrap;
		}
		
		@Override
		public void run() {
			for (int i = 0; i < 10; i++) {
				data.addThreadA();
			}
		}
	}
	
	static class ThreadB extends Thread {
		private DataWrap data;
		
		public ThreadB(DataWrap dataWrap) {
			this.data = dataWrap;
		}
		
		@Override
		public void run() {
			for (int i = 0; i < 10; i++) {
				data.addThreadB();
			}
		}
	}
	
	public static void main(String[] args) {
		//实现两个线程轮流对数据进行加一操作
		DataWrap dataWrap = new DataWrap();
		
		new ThreadA(dataWrap).start();
		new ThreadB(dataWrap).start();
	}

}
